package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.LoginMapper;
import com.itheima.pojo.PhoneDto;
import com.itheima.pojo.User;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class loginServiceImpl extends ServiceImpl<LoginMapper, User> implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    /**
     * 传入电话,获取验证码
     *
     * @param pd
     * @return
     */
    @Override
    public int getMsg(PhoneDto pd) {
        //1.生成一个验证码
          /*//uuid生成并截取
        String checkCode= (String) UUID.randomUUID().toString().subSequence(0,6);*/
        Random random = new Random();
        random.nextInt(10);
        String checkCode = "";
        for (int i = 0; i < 6; i++) {
            checkCode += (random.nextInt(10) + "");
        }
        String code1 = checkCode;
        Integer code = Integer.parseInt(code1);
        //需要try一下,万一失败了,抛出异常
        try {
            //2.将电话和验证码传入类方法中,发送短信到用户手机

            //  SendSms.sendMsg(pd.getPhone(), code);
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常,返回一个 0
            return 0;
        }
        //短信发送成功,返回一个checkCode
        return code;
    }

    /**
     * @param pd
     * @return
     */
    @Override
    public User loginUser(PhoneDto pd) {
        //1.查询到该手机是否存在数据库
        LambdaQueryWrapper<User> wapper = new LambdaQueryWrapper<>();
        wapper.eq(User::getPhone, pd.getPhone());
        User user = loginMapper.selectOne(wapper);
        //如果没有查询到,注册一个
        if (user == null) {
            user = new User();
            user.setPhone(pd.getPhone());
            loginMapper.insert(user);
        }
        return user;
    }
}
